﻿@{
    ViewData["Title"] = "RoomReservationOrder";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style>
    .complaint-info {
        border: 1px solid #ccc;
        padding: 10px;
        margin: 20px;
    }

        .complaint-info p {
            margin: 5px 0;
        }
</style>

@* 查询条件 *@
<div class="layui-btn-container">
    <div class="layui-form layui-form-pane">
        <!-- 使用 layui-form-pane 来使元素在同一行显示 -->
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline" id="dateSelect">
                    <input type="text" autocomplete="off" id="startDate" class="layui-input" placeholder="开始日期">
                </div>
                <div class="layui-form-mid">-</div>
                <div class="layui-input-inline">
                    <input type="text" autocomplete="off" id="endDate" class="layui-input" placeholder="结束日期">
                </div>
            </div>
            <div class="layui-inline" style="margin-left: 10px;">
                <select name="orderTypes" lay-verify="required" lay-filter="orderTypes"></select>
            </div>
            <div class="layui-inline" style="margin-left:400px;">
                <select name="afterSaleState" lay-verify="required" lay-filter="afterSaleState"> </select>
            </div>
            <div class="layui-inline" style="margin-left: 10px;">
                <div class="layui-col-sm2" style="width:100px;">
                    <select name="choseOrder">
                        <option value="1">订单编号</option>
                        <option value="2">售后单号</option>
                    </select>
                </div>
                <div class="layui-col-sm2" style="width:150px;">
                    <input type="text" id="orderNumber" name="orderNumber" placeholder="请输入编号" class="layui-input">
                </div>
            </div>
        </div>
    </div>
</div>


@* 显示 *@
<table class="layui-table" id="demoTable" lay-filter="demoTable">
    <tbody>
    </tbody>
</table>
<div id="demo-laypage-all" style="justify-content: center;display: flex;"></div>

@* 操作列 *@
<script type="text/html" id="Operation">
    {{# if(d.afterSaleState === 1) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Refund">退款</a>
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Turn">拒绝</a>
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 2) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 3) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 4) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Refund">退款</a>
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 5) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 6) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Receive">收货</a>
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
    {{# if(d.afterSaleState === 7) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Refund">退款</a>
        <a href="#" class="link" style="color:cornflowerblue" lay-event="Details">详情</a>
    {{# } }}
</script>

@* 弹出层 *@
<div id="popupContent" style="display: none;">
    <div class="complaint-info">
        <p><strong>维权单信息</strong></p>
        <p>售后编号：<span name="afterSalesNumber">  </span> </p>
        <p>所属业务：<span name="orderTypes">  </span> </p>
        <p>关联订单编号：<span name="orderNumber">  </span> </p>
        <p>退款原因：<span>不想要了</span> </p>
    </div>
</div>
@* <script src="~/rooms/roomreservationorder.js"></script> *@
<script>
    layui.use(['element', 'table', 'form', 'layer', 'laypage', 'util', 'jquery'], function () {
        var form = layui.form;
        var element = layui.element;
        var layer = layui.layer;
        var util = layui.util;
        var $ = layui.jquery;
        var table = layui.table;
        var laydate = layui.laydate;
        var laypage = layui.laypage;

        //下拉框
        getSelect();

        // 获取当前日期
        var currentDate = new Date();

        // 计算默认的开始日期（当月的第一天）
        var startMonth = currentDate.getMonth();
        var startYear = currentDate.getFullYear();
        var startDate = new Date(startYear, startMonth, 1); // 当月的第一天

        // 计算默认的结束日期（下个月的第一天）
        var endMonth = startMonth + 1;
        var endYear = startYear;
        if (endMonth === 12) {
            endMonth = 0; // 月份从0开始，所以12表示1月
            endYear++;
        }
        var endDate = new Date(endYear, endMonth, 1); // 下个月的第一天

        // 格式化日期为 YYYY-MM-DD
        function formatDate(date) {
            var year = date.getFullYear();
            var month = date.getMonth() + 1; // getMonth返回的是0-11，所以要加1
            var day = date.getDate();
            return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
        }

        // 设置开始日期和结束日期的默认值
        $('#startDate').val(formatDate(startDate));
        $('#endDate').val(formatDate(endDate));


        // 定义一个空对象来存储搜索数据
        var searchData = {
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val(),
            orderTypes: 0,
            afterSaleState: 0,
            choseOrder: 0,
            orderNumber: "",
            pageIndex: 1,
            pageSize: 15
        };

        //显示
        show();

        // 在获取到数据后渲染分页
        show(function (total) {
            laypage.render({
                elem: 'demo-laypage-all', // 元素 id
                count: total, // 数据总数
                limit: searchData.size,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
                limits: [15, 20, 25, 30],
                prev: '<em>←</em>',
                next: '<em>→</em>',
                jump: function (obj, first) {
                    // 非首次加载时调用
                    if (!first) {
                        searchData.page = obj.curr;
                        searchData.size = obj.limit;
                        show(); // 再次调用 show() 方法更新数据
                    }
                }
            });
        });

        // 执行一个laydate实例
        laydate.render({
            elem: '#dateSelect',
            range: ['#startDate', '#endDate'],
            theme: 'molv',
            rangeLinked: true,
            done: function (value, date, endDate) {
                searchData.startDate = value.substring(0, 10);
                searchData.endDate = value.substring(13);
                show();
            }
        });

        // 监听订单类型下拉框的变化
        form.on('select(orderTypes)', function (data) {
            searchData.orderTypes = data.value;
            show();
        });

        // 监听售后状态下拉框的变化
        form.on('select(afterSaleState)', function (data) {
            searchData.afterSaleState = data.value;
            show();
        });

        //文本框失去焦点事件
        $('#orderNumber').on('blur', function () {
            searchData.choseOrder = $("[name=choseOrder]").val();
            searchData.orderNumber = $("[name=orderNumber]").val();
            show();
        });

        // 监听表格中的操作列事件
        table.on('tool(demoTable)', function (obj) {
            var data = obj.data;
            var event = obj.event;
            //维权单详情
            if (event === 'Details') {
                // 获取外部定义的弹出层内容
                var popupContent = document.getElementById('popupContent').innerHTML;
                // 页面层
                layer.open({
                    type: 1,
                    title: '详情',
                    area: ['600px', '220px'], // 宽高
                    content: popupContent,
                    success: function (index, layero) {
                        $("[name=afterSalesNumber]").html(data.afterSalesNumber)
                        $("[name=orderTypes]").html("订房")
                        $("[name=orderNumber]").html(data.orderNumber);
                        form.render();
                    }
                });
            }
            //收货
            else if (event === 'Receive') {
                $.post({
                    url: 'http://localhost:5174/api/AfterSale/UpdateAfterSaleState',
                    contentType: "application/json",
                    data: JSON.stringify({ AfterSalesOrderId: data.afterSalesOrderId, AfterSaleState: 7 }),
                    success: function (res) {
                        layer.msg('操作成功');
                        window.location.reload();
                    },
                    error: function () {
                        layer.msg('加载数据失败');
                    }
                });
            }
            //拒绝
            else if (event === 'Turn') {
                $.post({
                    url: 'http://localhost:5174/api/AfterSale/UpdateAfterSaleState',
                    contentType: "application/json",
                    data: JSON.stringify({ AfterSalesOrderId: data.afterSalesOrderId, AfterSaleState: 4 }),
                    success: function (res) {
                        layer.msg('操作成功');
                        window.location.reload();
                    },
                    error: function () {
                        layer.msg('加载数据失败');
                    }
                });
            }
            //退款
            else if (event === "Refund") {
                $.post({
                    url: 'http://localhost:5174/api/AfterSale/UpdateAfterSaleState',
                    contentType: "application/json",
                    data: JSON.stringify({ AfterSalesOrderId: data.afterSalesOrderId, AfterSaleState: 3 }),
                    success: function (res) {
                        layer.msg('操作成功');
                        window.location.reload();
                    },
                    error: function () {
                        layer.msg('加载数据失败');
                    }
                });
            }
        });

        //弹出层启动
        $('#btnOpen').on('click', function () {
            // 获取外部定义的弹出层内容
            var popupContent = document.getElementById('popupContent').innerHTML;

            // 页面层
            layer.open({
                type: 1,
                title: '房价计划',
                area: ['600px', '750px'], // 宽高
                content: popupContent,
                success: function (index, layero) {
                    form.render();
                }
            });
        })

        //弹出层添加
        form.on('submit(submitForm)', function (data) {

            //输入框默认值
            var today = new Date();
            var yyyy = today.getFullYear();
            var mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
            var dd = String(today.getDate()).padStart(2, '0');
            data.field.createdTime = yyyy + '-' + mm + '-' + dd;

            //阻止重复提交
            data.elem.disabled = true;
            $.ajax({
                url: 'http://localhost:5174/api/RoomHousingState/AddHousing',
                type: 'post',
                contentType: "application/json",
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                data: JSON.stringify(data.field),
                success: function (res) {
                    console.log(res.data)
                    // 添加成功后的操作
                    if (res.code > 0) {
                        layer.msg("添加成功");
                        show(from)
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            });

            layer.closeAll(); // 关闭所有弹出层
            return false; // 阻止表单的默认提交
        });

        // 弹出层取消按钮
        $(document).on('click', '[lay-on="closeFormBtn"]', function () {
            layer.closeAll(); // 关闭所有弹出层
        });

        //下拉框
        function getSelect() {
            // 使用 AJAX 动态加载下拉框选项
            $.get({
                url: 'http://localhost:5174/api/AfterSale/GetOrderTypes',
                success: function (data) {
                    // 成功获取数据后，动态生成下拉框选项
                    var select = $('select[name="orderTypes"]');
                    select.empty(); // 清空下拉框当前的选项
                    // 添加默认选项
                    select.append('<option value="0">全部业务</option>');
                    // 添加 AJAX 返回的数据作为选项
                    $.each(data, function (index, item) {
                        select.append('<option value="' + item.value + '">' + item.name + '</option>');
                    });


                    // 重新渲染表单
                    form.render('select');
                },
                error: function () {
                    layer.msg('加载数据失败');
                }
            });
            $.get({
                url: 'http://localhost:5174/api/AfterSale/GetAfterSaleState',
                success: function (data) {

                    var select = $('select[name="afterSaleState"]');
                    select.empty();

                    select.append('<option value="0">全部售后状态</option>');

                    $.each(data, function (index, item) {
                        select.append('<option value="' + item.value + '">' + item.name + '</option>');
                    });

                    form.render('select');
                },
                error: function () {
                    layer.msg('加载数据失败');
                }
            });
        }

        //定义显示方法
        function show(callback) {

            //获取显示值
            $.post({
                url: 'http://localhost:5174/api/AfterSale/GetALLAfterSale',
                contentType: "application/json",
                data: JSON.stringify(searchData),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {

                    total = res.data.total;

                    //定义枚举值到中文描述的映射对象
                    var orderTypesMap = {
                        1: '订房',
                        2: '商品',
                        3: '预约',
                        4: '收款码'
                    };

                    // 定义枚举值到中文描述的映射对象
                    var afterSaleStateMap = {
                        1: '待确认',
                        2: '退款处理中',
                        3: '已退款',
                        4: '退款失败',
                        5: '拒绝退款',
                        6: '等待买家退货',
                        7: '买家已退货',
                        8: '用户取消退款'
                    };
                    table.render({
                        elem: '#demoTable',
                        data: res.data.data,
                        cols: [[
                            { field: 'afterSalesNumber', title: '售后单号' },
                            {
                                field: 'afterSalesPrice', title: '售后金额', templet: function (d) {
                                    return '￥' + d.afterSalesPrice.toFixed(2)
                                }
                            },
                            {
                                field: 'afterSalesDate', title: '申请时间', templet: function (d) {
                                    return d.afterSalesDate.substring(0, 10)
                                }
                            },
                            { field: 'afterSalesClient', title: '顾客' },
                            {
                                field: 'orderTypes', title: '所属业务', templet: function (d) {
                                    return orderTypesMap[d.orderTypes];
                                }
                            },
                            {
                                field: 'afterSaleState', title: '退款状态', templet: function (d) {
                                    return afterSaleStateMap[d.afterSaleState];
                                }
                            },
                            { toolbar: '#Operation', width: 300, title: '操作' }
                        ]]
                    });
                    // 如果传入了回调函数，则执行回调函数，并传入总条数
                    if (typeof callback === 'function') {
                        callback(total);
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            })
        }
    });
</script>